package tech.xiaozai.exam.security.authentication;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-23 08:37
 *
 *  仿照security的UsernamePasswordAuthenticationFilter来写
 */
public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     *  只对post请求处理登录
     */
    private Boolean postOnly = true;


    public static final String SECURITY_JSON_USERNAME_KEY="username";
    public static final String SECURITY_JSON_PASSWORD_KEY="password";


    private String usernameKey = SECURITY_JSON_USERNAME_KEY;
    private String passwordKey = SECURITY_JSON_PASSWORD_KEY;

    /**
     *
     * @param defaultFilterProcessesUrl  要传入本过滤器的默认处理路径
     */
    public MyUsernamePasswordAuthenticationFilter(String defaultFilterProcessesUrl){
        super(defaultFilterProcessesUrl);

    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {


        System.out.println("xxxxxxxxxxxxxxxxxxxxxx");

        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        // request.getReader().readLine()  -> jsonText ->  object(username,password)
        String body = ServletUtil.getBody(request);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String username = jsonObject.getStr(usernameKey);
        String password = jsonObject.getStr(passwordKey);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request,
                              UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
